package com.renwei.yunlong.activity.work;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.trace.model.SortType;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.CommonBean;
import com.renwei.yunlong.bean.WorkTrackBean;
import com.renwei.yunlong.event.WorkPageRefreshEvent;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.DateTimeUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.view.RoundView;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.PermissionUtil;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

import static com.renwei.yunlong.R.id.btn_confirm;

public class WorkMapActivity extends BaseActivity implements SensorEventListener,
        RationaleListener, PermissionListener, HttpTaskListener, View.OnClickListener {

    public static final int FROM_CHUFA = 1001;
    public static final int FROM_DAODA = 1002;

    @Bind(R.id.bmapView)
    MapView mMapView;
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.cardview)
    CardView cardview;
    @Bind(R.id.iv_loca)
    ImageView ivLoca;
    @Bind(R.id.iv_clean)
    ImageView ivClean;
    @Bind(btn_confirm)
    Button btnConfirm;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.tv_time)
    TextView tvTime;
    private SensorManager mSensorManager;
    private BaiduMap mBaiduMap;
    private LocationClient mLocClient;
    private int mCurrentDirection;
    private double lastX;
    private MyLocationData locData;
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private float mCurrentAccracy;
    private LatLng llMe;
    boolean isFirstLoc = true; // 是否首次定位
    private String requestId;
    private String eventId;
    private int from;
    private BitmapDescriptor iconStart;
    private BitmapDescriptor iconEnd;
    private Marker meMarker;
    private boolean isReset;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_ddmap);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.black_top), 0);
        PermissionUtil.checkSinglePermission(this, this, this, Permission.LOCATION);
        requestId = getIntent().getStringExtra("requestId");
        eventId = getIntent().getStringExtra("eventId");
        from = getIntent().getIntExtra("from", 0);
        initView();
    }

    private void initView() {
        //  初始化 其他控件
        btnConfirm.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        ivClean.setOnClickListener(this);
        ivLoca.setOnClickListener(this);
        tvTime.setText(DateTimeUtils.date2String(new Date(), "yyyy/MM/dd HH:mm EEEE"));

        // 初始化 百度地图
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        // 隐藏logo
        View child = mMapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);
        }
        // 隐藏 比例尺和加减号
        mMapView.showScaleControl(false);
        mMapView.showZoomControls(false);
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(getApplicationContext());
        mLocClient.registerLocationListener(new MyLocationListenner());
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mBaiduMap.hideInfoWindow();
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });

        if (from == FROM_CHUFA) {
            btnConfirm.setText("确认出发");
        } else if (from == FROM_DAODA) {
            btnConfirm.setText("确认到达");
            // 到达需要绘制轨迹
            initWorkLalng();
        }

    }

    private void initWorkLalng() {
        final View view = LayoutInflater.from(mContext).inflate(R.layout.view_map_icon, null);
        RelativeLayout rlMap = view.findViewById(R.id.rl_map);

        rlMap.setBackgroundResource(R.mipmap.icon_map_start);
        iconStart = BitmapDescriptorFactory.fromView(view);
        rlMap.setBackgroundResource(R.mipmap.icon_map_end);
        iconEnd = BitmapDescriptorFactory.fromView(view);

        HashMap<String, String> map = new HashMap<>();
        map.put("requestId", requestId);
        ServiceRequestManager.getManager().getWorkLatLng(this, "", JsonMapUtil.mapToJson(map), this);
    }

    /**
     * 确定
     */
    private void confirm() {
        String address = tvAddress.getText().toString();
        if (TextUtils.isEmpty(address)) {// 未开启定位权限 或者 没有网络状态
            showCenterInfoMsg("未开启定位权限或者网络状态较差");
            return;
        }
        if (from == FROM_CHUFA) {
            HashMap<String, String> map = new HashMap<>();
            map.put("requestId", requestId);
            map.put("eventId", eventId);
            map.put("longitude", mCurrentLon + "");
            map.put("latitude", mCurrentLat + "");
            map.put("placeName", address);
            if ("1".equals(companyType)) {
                map.put("ownerCode", ownerBean.getRows().getOwnerCode());
                map.put("currentUserId", ownerBean.getRows().getEmployeeId());
            } else if ("2".equals(companyType)) {
                map.put("ownerCode", serviceLoginBean.getRows().getServiceProviderCode());
                map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
            }
            ServiceRequestManager.getManager().setWorkChufa(this, JsonMapUtil.mapToJson(map), this);
        } else if (from == FROM_DAODA) {
            ServiceRequestManager manager = ServiceRequestManager.getManager();
            HashMap<String, String> map = new HashMap<>();
            map.put("requestId", requestId);
            map.put("eventId", eventId);
            map.put("longitude", "" + mCurrentLon);
            map.put("latitude", "" + mCurrentLat);
            map.put("placeName", address);
            if ("1".equals(companyType)) {
                map.put("ownerCode", ownerBean.getRows().getOwnerCode());
                map.put("currentUserId", ownerBean.getRows().getEmployeeId());
            } else if ("2".equals(companyType)) {
                map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
                map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
            }
            manager.CommitArrivedPosition(this, JsonMapUtil.mapToJson(map), this);
        }
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    protected void onStop() {
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            locData = new MyLocationData.Builder()
                    .accuracy(mCurrentAccracy)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(mCurrentLat)
                    .longitude(mCurrentLon).build();
            mBaiduMap.setMyLocationData(locData);
        }
        lastX = x;

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    @Override
    public void onSuccess(int requestId, String result) {
        if (requestId == 1) {
            CommonBean bean = new Gson().fromJson(result, CommonBean.class);
            if (bean.getMessage().getCode() == 200) {
                finish();
                EventBus.getDefault().post(new WorkPageRefreshEvent());
                showCenterSuccessMsg("操作成功");
            } else {
                showCenterInfoMsg(bean.getMessage().getMessage());
            }
        } else if (requestId == 2) {
            WorkTrackBean workTrackBean = new Gson().fromJson(result, WorkTrackBean.class);
            if (workTrackBean.getMessage().getCode() == 200) {
                setMapTrack(workTrackBean);
            }
        }
    }

    // 开始绘制轨迹
    private void setMapTrack(WorkTrackBean workTrackBean) {
        List<LatLng> points = new ArrayList<>();
        List<WorkTrackBean.RowsBean.AppPositionLocationListBean> locationList = workTrackBean.getRows().getAppPositionLocationList();
        if (locationList != null) {
            if (locationList.size() == 1) {
                points.add(new LatLng(Double.parseDouble(locationList.get(0).getLatitude()),
                        Double.parseDouble(locationList.get(0).getLongitude())));
                points.add(new LatLng(Double.parseDouble(locationList.get(0).getLatitude()),
                        Double.parseDouble(locationList.get(0).getLongitude())));
            } else {
                for (WorkTrackBean.RowsBean.AppPositionLocationListBean bean : locationList) {
                    points.add(new LatLng(Double.parseDouble(bean.getLatitude()), Double.parseDouble(bean.getLongitude())));
                }
            }
            drawHistoryTrack(points, SortType.asc);
        } else {
            showCenterInfoMsg("当前未查询到工单轨迹");
        }
//        points.add(new LatLng(30.288398,120.120577));
//        points.add(new LatLng(30.288523,120.122733));
//        points.add(new LatLng(30.288679,120.124853));
//        points.add(new LatLng(30.288585,120.126003));
//        points.add(new LatLng(30.287525,120.125931));
//        points.add(new LatLng(30.285436,120.126075));
//        points.add(new LatLng(30.284531,120.126183));
//        points.add(new LatLng(30.283845,120.126147));
//        points.add(new LatLng(30.283221,120.126291));
//        points.add(new LatLng(30.282747,120.126244));
//        drawHistoryTrack(points,SortType.asc);
    }

    /**
     * 绘制历史轨迹
     */
    public void drawHistoryTrack(List<LatLng> points, SortType sortType) {
        // 绘制新覆盖物前，清空之前的覆盖物
        mBaiduMap.clear();
        if (points == null || points.size() == 0) {
            return;
        }

//        if (points.size() == 1) {
//            OverlayOptions startOptions = new MarkerOptions().position(points.get(0)).
//                    icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_map_loc_other))
//                    .zIndex(9).draggable(true);
//            mBaiduMap.addOverlay(startOptions);
//            animateMapStatus(points.get(0), 18.0f);
//            return;
//        }

        LatLng startPoint;
        if (sortType == SortType.asc) {
            startPoint = points.get(0);
        } else {
            startPoint = points.get(points.size() - 1);
        }

        // 添加起点图标
        OverlayOptions startOptions = new MarkerOptions()
                .position(startPoint).icon(iconStart)
                .zIndex(9).draggable(true);

        // 添加路线（轨迹）
        OverlayOptions polylineOptions = new PolylineOptions().width(10)
                .color(Color.BLUE).points(points);

        mBaiduMap.addOverlay(startOptions);
//        mBaiduMap.addOverlay(endOptions);
        Overlay polylineOverlay = mBaiduMap.addOverlay(polylineOptions);

//        OverlayOptions markerOptions =
//                new MarkerOptions().flat(true).anchor(0.5f, 0.5f).icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_map_loc_other))
//                        .position(points.get(points.size() - 1))
//                        .rotate((float) getAngle(points.get(0), points.get(1)));
//        Marker mMoveMarker = (Marker) mBaiduMap.addOverlay(markerOptions);

        animateMapStatus(points);
    }


    public void animateMapStatus(List<LatLng> points) {
        if (null == points || points.isEmpty()) {
            return;
        }
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        for (LatLng point : points) {
            builder.include(point);
        }
        MapStatusUpdate msUpdate = MapStatusUpdateFactory.newLatLngBounds(builder.build());
        mBaiduMap.animateMapStatus(msUpdate);
    }


    @Override
    public void onException(int requestId, String code) {
    }

    @Override
    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
        AndPermission.rationaleDialog(this, rationale).show();
    }

    @Override
    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
        switch (requestCode) {
            case PermissionUtil.LOCATION:
                initView();
                confirm();
                break;
            default:
                break;

        }
    }

    @Override
    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(this, PermissionUtil.SETTING_CODE).show();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_loca:// 回到当前位置
                MapStatus mMapStatus = new MapStatus.Builder()
                        .target(new LatLng(mCurrentLat, mCurrentLon))
                        .zoom(16)
                        .build();
                //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                //改变地图状态
                mBaiduMap.animateMapStatus(mMapStatusUpdate);
                break;
            case R.id.iv_clean:
                if (isReset) {
                    isReset = false;
                    cardview.setVisibility(View.VISIBLE);
                    ivClean.setImageResource(R.mipmap.icon_map_clean);
                } else {
                    isReset = true;
                    cardview.setVisibility(View.GONE);
                    ivClean.setImageResource(R.mipmap.icon_map_reset);
                }
                break;
            case btn_confirm:
                PermissionUtil.checkOnePermission(this, PermissionUtil.LOCATION, WorkMapActivity.this, WorkMapActivity.this, Permission.LOCATION);
                break;
            default:
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PermissionUtil.SETTING_CODE:
                MapStatus mMapStatus = new MapStatus.Builder()
                        .target(new LatLng(mCurrentLat, mCurrentLon))
                        .zoom(16)
                        .build();
                //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                //改变地图状态
                mBaiduMap.animateMapStatus(mMapStatusUpdate);
                break;
            default:
                break;

        }
    }

    /**
     * 定位SDK监听函数
     */
    private class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map icon_work_watch 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            String address = location.getAddress().address;
            tvTime.setText(DateTimeUtils.date2String(new Date(), "yyyy/MM/dd HH:mm EEEE"));
            if (!TextUtils.isEmpty(address)) {
                if (!address.equals(tvAddress.getText().toString())) {
                    LogUtil.e("设置地址");
                    tvAddress.setText(address);
                    tvAddress.setSelected(true);
                }
            }
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();
            if (llMe == null) {
                llMe = new LatLng(mCurrentLat, mCurrentLon);
                addMapOver(false);
            } else {
                llMe = new LatLng(mCurrentLat, mCurrentLon);
                if (meMarker != null) {
                    meMarker.setPosition(llMe);
                }
            }

            mCurrentAccracy = location.getRadius();
            locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(16.0f);
                // 设置地图参数
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }

        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    private void addMapOver(final boolean isFirst) {
        final View view = LayoutInflater.from(mContext).inflate(R.layout.view_map_icon, null);
        RelativeLayout rlMap = view.findViewById(R.id.rl_map);
        rlMap.setBackgroundResource(R.mipmap.icon_map_loc_me);
        final RoundView rvMap = view.findViewById(R.id.rv_head);
        String url = "1".equals(companyType) ? Api.$().OWNER_FILE_URL + ownerBean.getRows().getAvatar()
                : Api.$().SERVICE_FILE_URL + serviceLoginBean.getRows().getAvatar();
        Glide.with(mContext).load(url)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        rvMap.setImageResource(R.mipmap.icon_header_default);
                        BitmapDescriptor locMe = BitmapDescriptorFactory.fromBitmap(getViewBitmap(view));
                        MarkerOptions ooMe = new MarkerOptions().position(llMe).icon(locMe)
                                .zIndex(1).draggable(true);
                        // 掉下动画
                        // ooMe.animateType(MarkerOptions.MarkerAnimateType.drop);

                        meMarker = (Marker) mBaiduMap.addOverlay(ooMe);
                        meMarker.setToTop();
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (isFirst) {
                                    BitmapDescriptor locMe = BitmapDescriptorFactory.fromBitmap(getViewBitmap(view));
                                    MarkerOptions ooMe = new MarkerOptions().position(llMe).icon(locMe)
                                            .zIndex(1).draggable(true);
                                    // 掉下动画
                                    // ooMe.animateType(MarkerOptions.MarkerAnimateType.drop);

                                    meMarker = (Marker) mBaiduMap.addOverlay(ooMe);
                                    meMarker.setToTop();
                                } else {
                                    addMapOver(true);
                                }
                            }
                        }, 500);
                        return false;
                    }
                }).into(rvMap);
    }

    /**
     * 把View转换成Bitmap类型
     *
     * @return
     * @paramaddViewContent要转换的View
     */
    public Bitmap getViewBitmap(View addViewContent) {
        addViewContent.setDrawingCacheEnabled(true);
        addViewContent.measure(
                View.MeasureSpec.makeMeasureSpec(0,
                        View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0,
                        View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0,
                addViewContent.getMeasuredWidth(),
                addViewContent.getMeasuredHeight());


        addViewContent.buildDrawingCache();
        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
        return bitmap;
    }

    public static void OpenActivity(Context context, String requestId, String eventId, int from) {
        Intent intent = new Intent(context, WorkMapActivity.class);
        intent.putExtra("requestId", requestId);
        intent.putExtra("eventId", eventId);
        intent.putExtra("from", from);
        context.startActivity(intent);
    }


}
